(function($){
	var Page;
	Page = (function(){

		//将属性转换为数据库字段
		function getDbField(sortName)
		{
			if(!sortName || sortName == null) return undefined;
			
			var fieldArray = sortName.split('');
			var dbField = "";
			
			for(var i = 0 ;i < fieldArray.length; i++)
			{
				var c = fieldArray[i];
				if(isUpper(c)) c = '_' + c.toLowerCase();
				dbField += c;
			}
			return dbField;
		}
		
		//判断是否是大写字母
		function isUpper(c)
		{
			return c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90;
		}
		
		function Page(settings,table){
            this.settings = settings;
            this.table = table;//表格
			this.renderTableFrame();
			this.renderPageBottom();
			this.initSort();
			this.initEvent();
			this.currPage = settings.currPage;
		}

		//点击下一页方法
		Page.prototype.nextPage = function(e){
			this.currPage++;
			$(this.table).data("page").loadData();
		};

		//点击上一页方法
		Page.prototype.prePage = function(e){
            this.currPage--;
			$(this.table).data("page").loadData();
		};


        //点击第一页方法
        Page.prototype.firstPage = function(e){
            this.currPage = 1;
            $(this.table).data("page").loadData();
        };

        //点击最后一页
        Page.prototype.lastPage = function(e){
            this.currPage = this.totalPage;
            $(this.table).data("page").loadData();
        };

		//点击页面方法
		Page.prototype.turn = function(e){
            this.currPage = parseInt($(e.target).attr('page'));
			$(this.table).data("page").loadData();
		};

        //跳转指定页码
        Page.prototype.go = function(pageNum){
            this.currPage = pageNum;
            if(this.currPage.length > 0) {
                if(this.currPage > this.totalPage || this.currPage < 0) {
                    BootstrapDialog.alert({
                        title: '系统操作提示!',
                        message: '请输入正确的跳转的页数',
                        closable:true,
                        type: BootstrapDialog.TYPE_DANGER,
                        size:BootstrapDialog.SIZE_SMALL,
                        buttonLabel: '关 闭'
                    });
                } else {
                    $(this.table).data("page").loadData();
                }
            } else {
                BootstrapDialog.alert({
                    title: '系统操作提示!',
                    message: '请输入要跳转的页数',
                    closable:true,
                    type: BootstrapDialog.TYPE_DANGER,
                    size:BootstrapDialog.SIZE_SMALL,
                    buttonLabel: '关 闭'
                });
            }
        };
		
		//当表格有checkbox全选方法
		Page.prototype.checkAll = function(){
			$(this.table).find(":checkbox").prop("checked",$(this.table).find("[name=checkAll]").prop("checked"));
		};
		
		//当表格有checkbox，每行选方法
		Page.prototype.check = function(){
			with($(this.table))
			{
				find("thead :checkbox").prop("checked",find("tbody :checkbox").size() == find("tbody :checkbox:checked").size());
			}
			
		};
		
		//渲染分页栏
		Page.prototype.renderPageBottom = function(rowSize){
            if(this.totalPage && this.totalPage > 1)
			{
                var pageBottom = $(this.table).siblings(".row[pagebottom]");
                if(pageBottom.length == 0)
                {
                    $(this.table).after('<div class="row" style="cursor: pointer;" pagebottom><div recordtipbar class="col-md-3 col-sm-12"></div><div paginationbar class="col-md-9 col-sm-12"></div></div>')
                    pageBottom = $(this.table).siblings(".row[pagebottom]");
                }
                pageBottom.find("div[recordtipbar]").empty().html('<div role="status">显示 '+ ((this.currPage-1) * 10 + 1) +' 到 '+ (((this.currPage-1) * 10) + rowSize) +' 共 '+ this.total +' 条</div>');
                pageBottom.find("div[paginationbar]").empty();
				var html = "";
                if(this.settings.useGo == undefined || this.settings.useGo == true)
                {
                    html += '<div style="border: 1px solid #ddd;width: 15%;float:right;font-size:12px;height: 29px;margin: 0px 0 10px 3px;">';
                    html += '<span name="goPageBtn" style="width:32%;border-right: 1px solid #ddd;margin: 0;text-align: center;display: block;float: left;color: #337ab7;vertical-align: middle;line-height: 27px;">GO</span>';
                    html += '<input type="text" name="goPageNum" style="width: 40%;border: 0px;height: 100%;text-align: center;" value="' + this.currPage + '"/>';
                    html += '<span style="width:27%;border-left: 1px solid #ddd;margin: 0;display: block;float: right;color: #337ab7;vertical-align: middle;line-height: 27px;text-align: center;">页</span></div>';
                }
                html += '<ul class="pagination pagination-sm pull-right">';
                html += '<li class="'+ (this.currPage <=1 ? 'disabled' : '') +'"><a first><i class="fa fa-angle-double-left"></i></a></li>';
				html += '<li class="'+ (this.currPage <=1 ? 'disabled' : '') +'"><a pre><i class="fa fa-angle-left"></i></a></li>';

                var beginPage = (this.currPage - 3 > 0 ? this.currPage - 3 : 1);
				var endPage = (this.currPage + 3 <= this.totalPage ? this.currPage + 3 : this.totalPage);
				for(var i = beginPage; i <= endPage; i++){
					if(i == this.currPage)
					{
						html += '<li class="active disabled">';
					}
					else
					{
						html += '<li>';
					}
					html += '<a page="' + i + '">' + i + '</a></li>';
				}
				html += '<li class="'+ (this.currPage >= this.totalPage ? 'disabled' : '') +'"><a next><i class="fa fa-angle-right"></i></a></li>';
                html += '<li class="'+ (this.currPage >= this.totalPage ? 'disabled' : '') +'"><a last><i class="fa fa-angle-double-right"></i></a></li>';
                html += '</ul>';
                pageBottom.find("div[paginationbar]").append(html);
			}
            else
            {
                $(this.table).siblings(".row[pagebottom]").remove();
            }
		};
		
		//渲染表格头
		Page.prototype.renderHeader = function(){
			
			var html = '<tr>';
			var type = this.settings.type;
			for(var i = 0; i < this.settings.columns.length;i++)
			{
				var col = this.settings.columns[i];
				var style = col.style;
				var classes = col.class;
				html += '<th';

				if(style && style != '')html += ' style="' + style + '"';
			
				if(classes && classes != '')html += ' class="' + classes + '"';
				
				if(col.checkbox) 
				{
					html += '><input type="checkbox" name="checkAll" style="padding-left:8px;" /></th>';
				}
				else if(col.radio)
				{
					html += '></th>';
				}
				else
				{
                    //判断是否可以排序
					if(col.sortable)
					{
                        html += ' sort-field='+ col.field +'  class="sorting">';
					}
					else
					{
						html += '>';
					}

                    if(col.icon && col.icon.class)
                    {
                        if(!col.icon.position || col.icon.position == "right" ) html += col.name + '&nbsp;<i class="'+ col.icon.class +'"></i>';
                        else html += '<i class="'+ col.icon.class +'"></i>&nbsp;' + col.name;
                    }
                    else
                    {
                        html += col.name;
                    }
                    html += '</th>';
				}
			}
			
			html += '</tr>';
			$(this.table).find('table thead').html(html);
			return html;
		};
		
		//渲染表格整体结构
		Page.prototype.renderTableFrame = function(){
			$(this.table).html('<table style="' + (this.settings.style ? this.settings.style : '') + '" class="table table-striped table-bordered table-hover"><thead></thead><tbody></tbody></table>');
			this.renderHeader();
		};
		
		
		//渲染数据
		Page.prototype.renderData = function(data){
            var _this = this;
			var html = '';
			this.dataMap = {};
			var columns = this.settings.columns;
			var type = this.settings.type;
			$(this.table).find('table tbody').html('');
            if(data)
            {
                $.each(data,function(idx){
                    html+='<tr data-index="' + idx + '">';
                    var obj = this;
                    $.each(columns,function(){

                        var colVal = obj[this.field];
                        if((this.default != undefined && this.default != null)
                            && (colVal == "null"|| colVal == null
                            || colVal == "undefined" || colVal == undefined)) colVal = this.default;

                        var style = "";
                        var title = colVal;
                        if(this.overflow && this.overflow == "hide")
                        {
                            style += "text-overflow: ellipsis;white-space: nowrap;overflow: hidden;";
                        }
                        html += '<td style="'+ style +'" ';
                        if(this.checkbox)
                        {
                            html += ">";
                            $(_this.table).find("thead :checkbox").prop("checked",false);
                            html += "<input type='checkbox' name='" + this.field + "' value='" + colVal + "'/>";
                        }
                        else if(this.radio)
                        {
                            html += ">";
                            html += "<input type='radio' name='" + this.field + "' value='" + colVal + "'/>";
                        }
                        else if(this.formatting)
                        {
                            html += ">";
                            html += this.formatting(idx,obj);
                        }
                        else
                        {
                            html += 'title="'+ colVal +'" >';
                            html += colVal;
                        }
                        html += "</td>";
                    });
                    html += '</tr>';
                    _this.dataMap[idx] = this;
                });
            }
			$(this.table).find('table tbody').html(html);
            this.settings.afterCallback && this.settings.afterCallback(this, this.dataMap);
		};

        Page.prototype.getPageSize = function(){
            if(this.settings.pageSize){
                return this.settings.pageSize;
            }
            return 10;
        };

		//获取数据
		Page.prototype.loadData = function(){
			var pageResult = null;
			var reqData = undefined;
            if(this.settings.searchParams) {
                if(typeof  this.settings.searchParams == "string") {
                    reqData = this.settings.searchParams;
                }
                else {
                    reqData = $.param(this.settings.searchParams)
                }
            } else {
                reqData = "";
            }

            var sortField = getDbField(this.settings.sortField);
            sortField = (sortField ? sortField : "");

            var sortBy = (this.settings.sortBy ? this.settings.sortBy : "");

            reqData += (reqData == "" ? "" : "&");
            reqData += "sortField=" + sortField;
            reqData += "&sortBy=" + sortBy;
            reqData += "&pageSize=" + this.getPageSize();
            reqData += "&pageNum=" + (this.currPage ? this.currPage : 0);

			$.ajax({
				url:this.settings.url,
				data:reqData,
				async:false,
				dataType:'json',
				type:'post',
                beforeSend:function(){
                    //Metronic.blockUI({
                    //    target: $(pageObj.table),
                    //    overlayColor: 'rgb(178, 173, 173)',
                    //    animate: true
                    //});
                },
				success:function(resp){
					pageResult = resp;
				},
                complete:function(){
                   // Metronic.unblockUI($(pageObj.table));
                }
			}); 
			this.currPage = pageResult.pageNum;
			this.totalPage = pageResult.pages;
			this.total = pageResult.total;
			this.renderData(pageResult.rows);
			this.renderPageBottom((pageResult.rows ? pageResult.rows.length : 0));

		};
		
		//根据查询参数重新加载数据
		Page.prototype.reloadData = function(settings){
            if(settings)
            {
                $(this.table).find('[sort-field]').removeClass("sorting_desc").removeClass("sorting_asc").addClass("sorting");
                this.settings.sortField = undefined;
                this.settings.sortBy = undefined;
                this.settings.searchParams = settings.searchParams;
                this.settings.pageSize = settings.pageSize;
                this.currPage = settings.currPage;
            }
			this.loadData();
		};

		//获取选中的数据
		Page.prototype.getSelected = function(){
            var _this = this;
			var selectedData = new Array();
			$.each($(this.table).find("tbody :checked"),function(){
				var dataIndex = $(this).closest("tr").attr("data-index") + "";
				selectedData.push(_this.dataMap[dataIndex]);
			});
			
			if(selectedData.length > 0)
			{
				if(this.settings.columns[0].checkbox) return selectedData;
				else if (this.settings.columns[0].radio) return selectedData[0];
			}
			else
			{
				return undefined;
			}
			
		};
		
		//排序
		Page.prototype.sortData = function(e){
            var _this = e.target;
			this.settings.sortField = $(_this).attr("sort-field");
			
			if($(_this).hasClass("sorting_asc"))
			{
				$(_this).removeClass("sorting_asc").addClass("sorting_desc");
                this.settings.sortBy = 'desc';
			}
			else if($(_this).hasClass("sorting_desc"))
			{
				$(_this).removeClass("sorting_desc").removeClass("sorting_asc").addClass("sorting");
                this.settings.sortField = undefined;
                this.settings.sortBy = undefined;
			}
			else
			{
				$(_this).removeClass("sorting").addClass("sorting_asc");
                this.settings.sortBy = 'asc';
			}
			$(this.table).find('[sort-field]').not(_this).removeClass("sorting_asc").removeClass("sorting_desc").addClass("sorting");
			this.loadData();
		};
		
		//初始化事件
		Page.prototype.initEvent = function(){
            var id = $(this.table).attr("id");
            var _this = this;
            $('#'+ id +' th[sort-field]').click(function(e){
                _this.sortData(e);
            });
            $(document).on('click', '#'+ id +' ~ div[pagebottom] .pagination li a[first]', function(e){
                if(!$(this).closest("li").hasClass("disabled")) _this.firstPage(e);
            });
            $(document).on('click', '#'+ id +' ~ div[pagebottom] .pagination li a[last]', function(e){
                if(!$(this).closest("li").hasClass("disabled")) _this.lastPage(e);
            });
			$(document).on('click', '#'+ id +' ~ div[pagebottom] .pagination li a:not([first]):not([pre]):not([next]):not([last])', function(e){
                if(!$(this).closest("li").hasClass("disabled")) _this.turn(e);
            });
			$(document).on('click', '#'+ id +' ~ div[pagebottom] .pagination li a[pre]', function(e){
                if(!$(this).closest("li").hasClass("disabled")) _this.prePage(e);
            });
			$(document).on('click', '#'+ id +' ~ div[pagebottom] .pagination li a[next]', function(e){
                if(!$(this).closest("li").hasClass("disabled")) _this.nextPage(e);
            });

            $(document).on('click', '#'+ id +' ~ div[pagebottom] [name=goPageBtn]', function(e){
                _this.go($(e.target).siblings("[name=goPageNum]").val());

            });

            $(document).on('keyup', '#'+ id +' ~ div[pagebottom] [name=goPageNum]', function(e){
                $(e.target).val(parseInt($(e.target).val()) || '');
            });

            $(document).on('keydown', '#'+ id +' ~ div[pagebottom] [name=goPageNum]', function(e){
                if(e.keyCode == 13) {
                    _this.go($(e.target).val());
                }
            });

			$(document).on('change', '#'+ id +' [name=checkAll]', function(e) {
                _this.checkAll(e);
            });

			$(document).on('change', $('#'+ id +' tbody:checkbox'), function(e){
                _this.check(e);
            });

            $(document).on('click', '#'+ id +' table tbody tr td', function(e){
                var td = $(e.target).parent("td").andSelf();
                var tr = td.parent("tr");
                var tdIndex = parseInt(td.index());//用于获取事件对象索引
                var trIndex = tr.index();//用于获取数据索引
                var clickEvent = _this.settings.columns[tdIndex].events && _this.settings.columns[tdIndex].events.click;
                clickEvent && clickEvent(e, _this.dataMap[trIndex], trIndex);
            });
		};
		
		//初始化排序
		Page.prototype.initSort = function(){
            var _this = this;
			with($(this.table))
			{
                if(_this.settings.sortField)
                {
                    find('[sort-field]').removeClass("sorting_asc").removeClass("sorting_desc");
                    find('[sort-field="'+ _this.settings.sortField +'"]').addClass("sorting_" + _this.settings.sortBy.toLowerCase());
                }
			}
		};
		return Page;
	})();
	
	var methods = {
		init:function(options,needload){
            if(needload == null || needload == undefined) needload = true;
			var settings;
			settings = $.extend({
				url: "www.lly.com",
				type:''
			}, options);

			return this.each(function(){
            var paginating;
			var el = $(this);
			if(el.data("page") === undefined)
			{
                if(!$(this).attr("id"))
                {
                    $(this).attr("id", ((Math.random() + "").substring(2)));
                }
				paginating = new Page(settings,this);
                if(needload) paginating.loadData();

				
				el.data("page",paginating);
			 
				if (settings.onInitialized != null) 
				{
					settings.onInitialized.apply(paginating);
		        }
			}
			
	       return el;
		});
		},
	  destroy: function() {
  		  return this.each(function() {
    		  return $(this).removeData("page");
  		  });
    },
    next:function(){
    	this.data("page").nextPage();
    	
    },
    load:function(){
    	this.data("page").loadData();
    },
    reload:function(){
    	this.data("page").reloadData(arguments[0]);
    },
    selectedData:function(){
    	return this.data("page").getSelected();
    }
	};
	
	$.fn.page = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    } else {
      return $.error("Method " + method + " does not exist on jQuery.page");
    }
  };
})(jQuery);